package com.bootadmin.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.bootadmin.core.excepiton.ServiceException;
import com.bootadmin.core.web.BaseEmployeeLogin;
import com.bootadmin.core.web.SystemConstant;

import java.util.Date;
import java.util.Map;

/**
 * @author kongzm
 * @description: JwtUtils
 * @date 2022/1/15 23:18
 */
public class JwtUtils {
    /**
     * 创建JWT
     */
    public static String createJWT(BaseEmployeeLogin baseEmployeeLogin) throws Exception {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SystemConstant.JWT_SECERT);
            return JWT.create()
                    .withIssuer("Boot Admin")
                    .withIssuedAt(new Date(System.currentTimeMillis()))
                    .withExpiresAt(DateUtils.getEndTime())
                    .withClaim("baseEmployeeLogin", StringUtils.toJsonString(baseEmployeeLogin))
                    .sign(algorithm);
        } catch (JWTCreationException exception){
            exception.printStackTrace();
            throw new ServiceException(SystemConstant.FAILURE_CODE, "token生成失败");
        }
    }

    public static Map<String, Claim> verifyJWT(String token) throws ServiceException {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SystemConstant.JWT_SECERT);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("Boot Admin")
                    .build(); //Reusable verifier instance
            DecodedJWT decode = verifier.verify(token);
            return decode.getClaims();
        } catch (JWTVerificationException exception){
            exception.printStackTrace();
            throw new ServiceException(SystemConstant.LOGIN_FAILURE_CODE, "token校验失败");
        }
    }

    public static BaseEmployeeLogin getLoginInfo(String token) {
        Map<String, Claim> res = verifyJWT(token);
        return JSONObject.parseObject(res.get("baseEmployeeLogin").asString(), BaseEmployeeLogin.class);
    }
}
